# Create your views here.
import datetime
import logging

from rest_framework import filters
from rest_framework import viewsets
from django.db.models import Q
from utils.pagination import MyPageNumberPagination, PageNumberPagination
from .models import Tasks
from . import serializers
from django_filters import rest_framework as django_filters

logger = logging.getLogger('dev07')


class TasksFilter(django_filters.FilterSet):
    demand_name = django_filters.CharFilter(field_name="demand_name", lookup_expr="icontains")
    demand_id = django_filters.NumberFilter(field_name="demand_id", lookup_expr="exact")
    task_id = django_filters.NumberFilter(field_name="task_id", lookup_expr="exact")
    task_name = django_filters.CharFilter(field_name="task_name", lookup_expr="icontains")
    task_type = django_filters.CharFilter(field_name="task_type", lookup_expr="icontains")
    estimate_time = django_filters.NumberFilter(field_name="estimate_time", lookup_expr="exact")
    left_time = django_filters.NumberFilter(field_name="left_time", lookup_expr="exact")
    status = django_filters.CharFilter(field_name="status", lookup_expr="icontains")
    assigned_to = django_filters.CharFilter(field_name="assigned_to", lookup_expr="icontains")
    version = django_filters.CharFilter(field_name="version", lookup_expr="icontains")

    class Meta:
        model = Tasks
        fields = ["demand_id", "demand_name", "task_id", "task_name", "task_type", "estimate_time", "left_time",
                  "status", "assigned_to", "version"]


class TasksViewSet(viewsets.ModelViewSet):
    """
    list:
    获取日报

    retrieve:
    获取日报详情数据

    update:
    更新日报信息

    """
    queryset = Tasks.objects.all()
    serializer_class = serializers.SearchTasksModelSerailizer

    # filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = TasksFilter
    # search_fields = ['=name', '=leader', '=id']
    ordering_fields = ['launch_time']
    pagination_class = PageNumberPagination
    # permission_classes = [permissions.IsAuthenticated]
    def get_queryset(self):
        queryset = super().get_queryset()
        if self.request.query_params.get('task_start_data'):
            task_start_data = datetime.datetime.strptime(self.request.query_params.get('task_start_data'), '%Y-%m-%d').date()
            task_end_data = datetime.datetime.strptime(self.request.query_params.get('task_end_data'), '%Y-%m-%d').date()
            queryset = queryset.filter(
                Q(est_started__gte=task_start_data, est_started__lte=task_end_data) |
                Q(deadline__gte=task_start_data, deadline__lte=task_end_data)
            )
            return queryset
        return queryset